<?php
/* prestalovenivoslideshow.php version 1.0 created by PrestaLove.com */
class prestalovenivoslideshow extends Module
{
	private $_listNivo = '';
	private $_html = '';
	private $_img_path = '/img/';
	
	public function __construct()
	{
		$this->name = 'prestalovenivoslideshow';
		$this->tab = 'front_office_features';
		$this->version = 1.0;
		$this->author = 'PrestaLove';
		$this->need_instance = 0;
		
		parent::__construct();
		
		$this->displayName = $this->l('PrestaLove Nivo Slideshow');
		$this->description = $this->l('Add Nivo Slideshow to your website.');
		$this->secure_key = Tools::encrypt($this->name);
	}

	public function install()
	{
		if(!parent::install() ||
			!$this->registerHook('header') ||
			!$this->registerHook('home') ||	
			!Configuration::updateValue('PRESTALOVE_NIVO_THEME', 'default') ||
			!Configuration::updateValue('PRESTALOVE_NIVO_EFFECT', 'random') ||
			!Configuration::updateValue('PRESTALOVE_NIVO_TIMER_DELAY', 3000) ||
			!Configuration::updateValue('PRESTALOVE_NIVO_SPEED', 500) ||
			!Configuration::updateValue('PRESTALOVE_NIVO_COLS', 8) ||
			!Configuration::updateValue('PRESTALOVE_NIVO_ROWS', 4) ||
			!Configuration::updateValue('PRESTALOVE_NIVO_AUTO_START', 1) ||
			!Configuration::updateValue('PL_NIVO_PAUSE_SLIDE_HOVER', 1) ||
			!Configuration::updateValue('PRESTALOVE_NIVO_CONTROLS', 0) ||
			!Configuration::updateValue('PL_NIVO_HIDE_CONTROLS_HOVER', 0) ||
			!Configuration::updateValue('PRESTALOVE_NIVO_NAV', 0) ||
			!Configuration::updateValue('PRESTALOVE_NIVO_NAVTHUMBS', 0) ||
			!Configuration::updateValue('PRESTALOVE_NIVO_IMAGE_WIDTH', 800) ||
			!Configuration::updateValue('PRESTALOVE_NIVO_IMAGE_HEIGHT', 300) ||
			!$this->installDB())
			return false;
		return true;
	}

	public function installDb()
	{
		Db::getInstance()->ExecuteS('
		CREATE TABLE IF NOT EXISTS `'._DB_PREFIX_.'pl_nivoslideshow` (
		  `id_plnivo` INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY ,
		  `filename` VARCHAR( 128 ) NOT NULL ,
		  `link` VARCHAR( 128 ) NOT NULL ,
		  `publish` TINYINT( 1 ) NOT NULL ,
		  `order` INT( 1 ) NOT NULL
		) ENGINE = MYISAM CHARACTER SET utf8 COLLATE utf8_general_ci;');
		
		Db::getInstance()->ExecuteS('
		CREATE TABLE IF NOT EXISTS `'._DB_PREFIX_.'pl_nivoslideshow_lang` (
		  `id_plnivo` INT NOT NULL ,
		  `id_lang` INT NOT NULL ,
		  `title` VARCHAR( 128 ) NOT NULL ,
		  `description` TEXT NOT NULL 
		) ENGINE = MYISAM CHARACTER SET utf8 COLLATE utf8_general_ci;');
		
		return true;
	}

	public function uninstall()
	{
		if(!parent::uninstall() || !$this->uninstallDB() ||
		!Configuration::deleteByName('PRESTALOVE_NIVO_THEME') ||
		!Configuration::deleteByName('PRESTALOVE_NIVO_EFFECT') ||
		!Configuration::deleteByName('PRESTALOVE_NIVO_TIMER_DELAY') ||
		!Configuration::deleteByName('PRESTALOVE_NIVO_SPEED') ||
		!Configuration::deleteByName('PRESTALOVE_NIVO_COLS') ||
		!Configuration::deleteByName('PRESTALOVE_NIVO_ROWS') ||
		!Configuration::deleteByName('PRESTALOVE_NIVO_AUTO_START') ||
		!Configuration::deleteByName('PL_NIVO_PAUSE_SLIDE_HOVER') ||
		!Configuration::deleteByName('PRESTALOVE_NIVO_CONTROLS') ||
		!Configuration::deleteByName('PL_NIVO_HIDE_CONTROLS_HOVER') ||
		!Configuration::deleteByName('PRESTALOVE_NIVO_NAV') ||
		!Configuration::deleteByName('PRESTALOVE_NIVO_NAVTHUMBS') ||
		!Configuration::deleteByName('PRESTALOVE_NIVO_IMAGE_WIDTH') ||
		!Configuration::deleteByName('PRESTALOVE_NIVO_IMAGE_HEIGHT')
		 )
			return false;
		return true;
	}

	private function uninstallDb()
	{
		Db::getInstance()->ExecuteS('DROP TABLE `'._DB_PREFIX_.'pl_nivoslideshow`');
		Db::getInstance()->ExecuteS('DROP TABLE `'._DB_PREFIX_.'pl_nivoslideshow_lang`');
		return true;
	}

	public function getContent()
	{
    	global $cookie;
		
		$this->_html .= '<h2>'.$this->l('PrestaLove Cycle Slideshow').'</h2>';

		if(Tools::isSubmit('submitPrestaLoveNivoConfig'))
    	{
			Configuration::updateValue('PRESTALOVE_NIVO_THEME', Tools::getValue('theme'));
			Configuration::updateValue('PRESTALOVE_NIVO_EFFECT', Tools::getValue('effect'));
			Configuration::updateValue('PRESTALOVE_NIVO_TIMER_DELAY', intval(Tools::getValue('time_delay')));
			Configuration::updateValue('PRESTALOVE_NIVO_SPEED', intval(Tools::getValue('speed')));
			Configuration::updateValue('PRESTALOVE_NIVO_COLS', intval(Tools::getValue('cols')));
			Configuration::updateValue('PRESTALOVE_NIVO_ROWS', intval(Tools::getValue('rows')));
			Configuration::updateValue('PRESTALOVE_NIVO_AUTO_START', intval(Tools::getValue('auto_start')));
			Configuration::updateValue('PL_NIVO_PAUSE_SLIDE_HOVER', Tools::getValue('pause_slide_hover'));	
			Configuration::updateValue('PRESTALOVE_NIVO_CONTROLS', Tools::getValue('controls'));		
			Configuration::updateValue('PL_NIVO_HIDE_CONTROLS_HOVER', Tools::getValue('hide_controls_hover'));			
			Configuration::updateValue('PRESTALOVE_NIVO_NAV', Tools::getValue('pager'));				
			Configuration::updateValue('PRESTALOVE_NIVO_NAVTHUMBS', Tools::getValue('pager_thumbs'));
			Configuration::updateValue('PRESTALOVE_NIVO_IMAGE_WIDTH', intval(Tools::getValue('image_width')));	
			Configuration::updateValue('PRESTALOVE_NIVO_IMAGE_HEIGHT', intval(Tools::getValue('image_height')));
			
			$this->_html .= $this->displayConfirmation($this->l('The configuration has been saved'));
		}
		
    	if(Tools::isSubmit('submitPrestaLoveNivo'))
    	{		
			$file = false;
			$filename = '';
			if (isset($_FILES['cs_img']) AND isset($_FILES['cs_img']['tmp_name']) AND !empty($_FILES['cs_img']['tmp_name']))
			{
				if ($error = checkImage($_FILES['cs_img'], 4000000))
					$this->_html .= displayConfirmation($error);
				elseif (!move_uploaded_file($_FILES['cs_img']['tmp_name'], dirname(__FILE__).'/img/cs-'.time().'-'.$_FILES['cs_img']['name']))
					$this->_html .= displayConfirmation($this->l('Error when move uploaded file'));
				else $filename = 'cs-'.time().'-'.$_FILES['cs_img']['name'];
				
			}
			// Add data to database
			$this->add($filename, Tools::getValue('title'), Tools::getValue('link'),  Tools::getValue('description'),  Tools::getValue('publish', 0));
			$this->_html .= $this->displayConfirmation($this->l('The image item has been added'));
    	}
		
			
    	if(Tools::isSubmit('submitPrestaLoveNivoRemove'))
    	{
      		$this->remove(Tools::getValue('id_plnivo', 0));      
      		$this->_html .= $this->displayConfirmation($this->l('The image item has been removed'));
    	}
		
		$flg_edit = 0;
		$cs_edit = array();
		if(Tools::isSubmit('submitPrestaLoveNivoEdit'))
    	{
      		$id_plnivo = Tools::getValue('id_plnivo', 0);
      		$cs_edit = $this->get($id_plnivo, $cookie->id_lang);
			$flg_edit = 1;
    	}
	
		if(Tools::isSubmit('submitPrestaLoveNivoEdited'))
    	{
			$filename = '';
			$category = Tools::getValue('category', 1);
			if (isset($_FILES['cs_img']) AND isset($_FILES['cs_img']['tmp_name']) AND !empty($_FILES['cs_img']['tmp_name']))
			{
				if ($error = checkImage($_FILES['cs_img'], 4000000))
					$this->_html .= displayConfirmation('Errrro');
				elseif (!move_uploaded_file($_FILES['cs_img']['tmp_name'], dirname(__FILE__).'/img/cs-'.time().'-'.$_FILES['cs_img']['name']))
					$this->_html .= displayConfirmation($this->l('Error move uploaded file'));
				else $filename = 'cs-'.time().'-'.$_FILES['cs_img']['name'];
			}

			$this->edit(Tools::getValue('id_plnivo_edit', 0), $filename, Tools::getValue('title'), Tools::getValue('link'), Tools::getValue('description'), Tools::getValue('publish', 1));
      
      		$this->_html .= $this->displayConfirmation($this->l('The image item has been edited'));
    	}
		
		if (Tools::isSubmit('id_plnivo') AND Tools::isSubmit('way') AND Tools::isSubmit('order'))
		{
			$this->_html .= $this->displayConfirmation($this->l('Order changed!'));
			if (Tools::getValue('way') == 0)
			{
				if (Db::getInstance()->Execute('
				UPDATE `'._DB_PREFIX_.'pl_nivoslideshow`
				SET `order` = '.((int)(Tools::getValue('order')) + 1).'
				WHERE `order` = '.((int)(Tools::getValue('order')))))
					Db::getInstance()->Execute('
					UPDATE `'._DB_PREFIX_.'pl_nivoslideshow`
					SET `order` = '.((int)(Tools::getValue('order'))).'
					WHERE `id_plnivo` = '.(int)(Tools::getValue('id_plnivo')));
			}
			elseif (Tools::getValue('way') == 1)
			{
				if(Db::getInstance()->Execute('
				UPDATE `'._DB_PREFIX_.'pl_nivoslideshow`
				SET `order` = '.((int)(Tools::getValue('order')) - 1).'
				WHERE `order` = '.((int)(Tools::getValue('order')))))
					Db::getInstance()->Execute('
					UPDATE `'._DB_PREFIX_.'pl_nivoslideshow`
					SET `order` = '.((int)(Tools::getValue('order'))).'
					WHERE `id_plnivo` = '.(int)(Tools::getValue('id_plnivo')));
			}
			Tools::redirectAdmin($currentIndex.'index.php?tab=AdminModules&configure='.$this->name.'&token='.Tools::getAdminTokenLite('AdminModules'));
		}
		
		// Configuration
		$this->_html .= '
   		<fieldset>
      		<legend><img src="../img/admin/cog.gif" alt="" title="" />'.$this->l('Configuation').'</legend>
			<form action="'.$_SERVER['REQUEST_URI'].'" method="post">
				<label>'.$this->l('Theme').'</label>
				<div class="margin-form">
					<select name="theme">
						<option';
						if(Configuration::get('PRESTALOVE_NIVO_THEME') == "default") $this->_html .= ' selected="selected" '; 
						$this->_html .= ' value="default">default</option>
						<option';
						if(Configuration::get('PRESTALOVE_NIVO_THEME') == "orman") $this->_html .= ' selected="selected" ';
						$this->_html .= ' value="orman">orman</option>
						<option';
						if(Configuration::get('PRESTALOVE_NIVO_THEME') == "pascal") $this->_html .= ' selected="selected" ';
						$this->_html .= ' value="pascal">pascal</option>
					</select>
					<p class="clear">'.$this->l('The style of Nivo Slideshow.').'</p>
				</div>
				
				<label>'.$this->l('Slideshow Effect').'</label>
				<div class="margin-form">
					<select id="cs-effect" name="effect">';
					$effect = array('random', 'sliceDownRight', 'sliceDownLeft', 'sliceUpRight', 'sliceUpLeft', 'sliceUpDown', 'sliceUpDownLeft', 'fold', 'fade', 'boxRandom', 'boxRain', 'boxRainReverse', 'boxRainGrow', 'boxRainGrowReverse');
					for($tmp=0; $tmp<count($effect); $tmp++) {
						$this->_html .= '<option ';
						if(Configuration::get('PRESTALOVE_NIVO_EFFECT') == $effect[$tmp]) $this->_html .= ' selected="selected" '; 
						$this->_html .= 'value="'.$effect[$tmp].'">'.$effect[$tmp].'</option>';
					}
					$this->_html .= '</select>
					<p class="clear">'.$this->l('The transition effect that will be used to change between images. Not all options below may be relevant depending on the effect.').'</p>
				</div>				
				<label>'.$this->l('Timer delay').'</label>
				<div class="margin-form">
					<input type="text" name="time_delay" value="'.Configuration::get('PRESTALOVE_NIVO_TIMER_DELAY').'" />
					<p class="clear">'.$this->l('The amount of time to show each slide in milliseconds (eg 3000)').'</p>
				</div>
				<label>'.$this->l('Animation Speed').'</label>
				<div class="margin-form">
					<input type="text" name="speed" value="'.Configuration::get('PRESTALOVE_NIVO_SPEED').'" />
					<p class="clear">'.$this->l('The speed of the transtion animation in milliseconds (eg 500)').'</p>
				</div>	
						
				<label>'.$this->l('Box (Cols x Rows)').'</label>
				<div class="margin-form">
					<input type="text" name="cols" value="'.Configuration::get('PRESTALOVE_NIVO_COLS').'" size="5" /> x <input type="text" name="rows" value="'.Configuration::get('PRESTALOVE_NIVO_ROWS').'" size="5" />
					<p class="clear">'.$this->l('The number of columns and rows to use in the "Box" transitions (eg 8 x 4)').'</p>
				</div>				
							
				<label>'.$this->l('Auto start').'</label>
				<div class="margin-form">
					<input type="checkbox" name="auto_start"';
					if(Configuration::get('PRESTALOVE_NIVO_AUTO_START')) $this->_html .= ' checked ';
					$this->_html .= 'value="1" /> '.$this->l('Start the slideshow').'
				</div>				
							
				<label>'.$this->l('Pause the slider on Hover').'</label>
				<div class="margin-form">
					<input type="checkbox" name="pause_slide_hover"';
					if(Configuration::get('PL_NIVO_PAUSE_SLIDE_HOVER')) $this->_html .= ' checked ';
					$this->_html .= 'value="1" />
				</div>	
							
				<label>'.$this->l('Controls').'</label>
				<div class="margin-form"><input type="checkbox" name="controls"';
					if(Configuration::get('PRESTALOVE_NIVO_CONTROLS')) $this->_html .= ' checked ';
					$this->_html .= 'value="1" /> '.$this->l('Determine if controls for the slideshow (next/previous) should appear').'
				</div>
							
				<label>'.$this->l('Hide Controls on Hover').'</label>
				<div class="margin-form">
					<input type="checkbox" name="hide_controls_hover"';
					if(Configuration::get('PL_NIVO_HIDE_CONTROLS_HOVER')) $this->_html .= ' checked ';
					$this->_html .= 'value="1" />
				</div>	
													
				<label>'.$this->l('Pager').'</label>
				<div class="margin-form">
					<input type="checkbox" name="pager"';
					if(Configuration::get('PRESTALOVE_NIVO_NAV')) $this->_html .= ' checked ';
					$this->_html .= 'value="1" /> '.$this->l('Determine if a pager for the slideshow (1|2|3) should appear.').'				
				</div>
													
				<label>'.$this->l('Image width').'</label>
				<div class="margin-form">					
					<input type="text" name="image_width" value="'.Configuration::get('PRESTALOVE_NIVO_IMAGE_WIDTH').'" />
					<p class="clear">'.$this->l('Width of images').'</p>
				</div>									
				<label>'.$this->l('Image height').'</label>
				<div class="margin-form">					
					<input type="text" name="image_height" value="'.Configuration::get('PRESTALOVE_NIVO_IMAGE_HEIGHT').'" />
					<p class="clear">'.$this->l('Height of images').'</p>
				</div>
				<center><input type="submit" name="submitPrestaLoveNivoConfig" value="'.$this->l('Save').'" class="button" /></center>
			</form>
		</fieldset> <br /><br />';
		
		// Add/Edit content 
		$defaultLanguage = (int)(Configuration::get('PS_LANG_DEFAULT'));
		$languages = Language::getLanguages(false);
		$iso = Language::getIsoById((int)($cookie->id_lang));
		$divLangName = 'title&curren;description';
		
		$isoTinyMCE = (file_exists(_PS_ROOT_DIR_.'/js/tiny_mce/langs/'.$iso.'.js') ? $iso : 'en');
		$ad = dirname($_SERVER["PHP_SELF"]);
		$this->_html .=  '
			<script type="text/javascript">	
			var iso = \''.$isoTinyMCE.'\' ;
			var pathCSS = \''._THEME_CSS_DIR_.'\' ;
			var ad = \''.$ad.'\' ;
			</script>
			<script type="text/javascript" src="'.__PS_BASE_URI__.'js/tiny_mce/tiny_mce.js"></script>
			<script type="text/javascript" src="'.__PS_BASE_URI__.'js/tinymce.inc.js"></script>';
		
			
   		$this->_html .= '
   		<fieldset>
      		<legend><img src="../img/admin/add.gif" alt="" title="" />'.$this->l('Add/Edit Image Slider').'</legend>
			<form action="'.$_SERVER['REQUEST_URI'].'" method="post" enctype="multipart/form-data" id="form">';
				if($flg_edit)
					$this->_html .= '<label>Image</label><div class="margin-form"><img src="'. _MODULE_DIR_ . $this->name.'/img/'.$cs_edit[0]['filename'].'" title="'. $cs_edit[0]['filename'] .'" width="200" /></div>';
				$this->_html .= '
				<label for="cs_img">'.$this->l('Upload Image').'</label>
				<div class="margin-form">
					<input id="cs_img" type="file" name="cs_img" />
				</div>';
			
				$this->_html .= '<label for="title">'.$this->l('Title').'</label>	
				<div class="margin-form">';
				
				foreach ($languages as $language)
				{
					$this->_html .= '
					<div id="title_'.$language['id_lang'].'" style="display: '.($language['id_lang'] == $defaultLanguage ? 'block' : 'none').';float: left;">
						<input type="text" name="title['.$language['id_lang'].']" id="title_text_'.$language['id_lang'].'" size="60" value="';
						if($flg_edit) {
							$cs_title = $this->gets($language['id_lang'], $cs_edit[0]['id_plnivo']);
							$this->_html .= $cs_title[0]['title'];
						}
					$this->_html .= '" />
					</div>';
				}
				$this->_html .= $this->displayFlags($languages, $defaultLanguage, $divLangName, 'title', true);
				
				
				$this->_html .= '</div><p class="clear"></p>';
        		$this->_html .= '
				<label for="link">'.$this->l('Link').'</label>      			
				<div class="margin-form">
					<input id="link" type="text" name="link" value="';
					if($flg_edit) $this->_html .= $cs_edit[0]['link'];
				$this->_html .= '" size="60" /> </div>
				<label for="description">'.$this->l('Description').'</label> 
				<div class="margin-form">';

				foreach ($languages as $language)
				{
					$this->_html .= '
					<div id="description_'.$language['id_lang'].'" style="display: '.($language['id_lang'] == $defaultLanguage ? 'block' : 'none').';float: left;">
						<textarea class="rte" cols="70" rows="10" id="description_textarea_'.$language['id_lang'].'" name="description['.$language['id_lang'].']">';
						if($flg_edit) {
							$cs_description = $this->gets($language['id_lang'], $cs_edit[0]['id_plnivo']);
							$this->_html .= htmlentities($cs_description[0]['description']);
						}
						$this->_html .= '</textarea>
					</div>';
				 }
				
				$this->_html .= $this->displayFlags($languages, $defaultLanguage, $divLangName, 'description', true);
				
				$this->_html .= '</div><p class="clear"></p>';
				$this->_html .= '<label for="publish">'.$this->l('Publish').'</label>
				<div class="margin-form">';
				if($flg_edit) {
					if($cs_edit[0]['publish']) {
						$this->_html .= '<input type="radio" name="publish" value="1" checked /><img title="Enabled" alt="Enabled" src="../img/admin/enabled.gif"/>
						<input type="radio" name="publish" value="0" /><img title="Disabled" alt="Disabled" src="../img/admin/disabled.gif"/>';
					}
					else {
						$this->_html .= '<input type="radio" name="publish" value="1" /><img title="Enabled" alt="Enabled" src="../img/admin/enabled.gif"/>
						<input type="radio" name="publish" value="0" checked /><img title="Disabled" alt="Disabled" src="../img/admin/disabled.gif"/>';
					}
				}
				else {
					$this->_html .= '<input type="radio" name="publish" value="1" checked /><img title="Enabled" alt="Enabled" src="../img/admin/enabled.gif"/>
					<input type="radio" name="publish" value="0" /><img title="Disabled" alt="Disabled" src="../img/admin/disabled.gif"/>';
				}
				$this->_html .= '</div>
				
				<p class="center"> ';
				if(!$flg_edit) {
					$this->_html .= '
					<input type="submit" name="submitPrestaLoveNivo" value="'.$this->l('  Add  ').'" class="button" /> ';
				}
				else {
					$this->_html .= '<input type="hidden" name="id_plnivo_edit" value="'.$cs_edit[0]['id_plnivo'].'" /><input type="submit" name="submitPrestaLoveNivoEdited" value="'.$this->l('  Edit  ').'" class="button" /> ';
				}
				$this->_html .= '
				</p>
			</form>
    	</fieldset><br />';
		
		
		// Display content
		$this->_html .= '
		<script type="text/javascript" src="../js/jquery/jquery.tablednd_0_5.js"></script>
		<script type="text/javascript" src="../modules/prestalovenivoslideshow/js/prestalovenivoslideshow.js"></script>
		<script type="text/javascript">PrestaloveNivoSlideshowDnD(\''.$this->secure_key.'\');</script>
		<fieldset>
	    	<legend><img src="../img/admin/details.gif" alt="" title="" />'.$this->l('List Image Slider').'</legend>
      		<table style="width:100%;" class="table tableDnD"  id="table-nivo">
        		<thead>
          			<tr>
						<th>'.$this->l('Order').'</th>
						<th>'.$this->l('Image').'</th>
						<th>'.$this->l('Title').'</th>
						<th>'.$this->l('Link').'</th>
						<th>'.$this->l('Description').'</th>
						<th>'.$this->l('Publish').'</th>
						<th>'.$this->l('Action').'</th>
				  	</tr>
        		</thead>
        		<tbody>';
          			$this->_html .=  $this->displayTableNivoSlideshow();
        		$this->_html .= '</tbody>
      		</table>
  		</fieldset>';

    	echo $this->_html;
	}
  

	private function add($filename, $title, $link, $description, $publish)
	{
	    $order = 0;
	    $max_order = Db::getInstance()->ExecuteS('
			SELECT max(`order`) as mo
			FROM '._DB_PREFIX_.'pl_nivoslideshow
		');		
		if($max_order[0]['mo'] != NULL) $order = $max_order[0]['mo'] + 1;
		
		Db::getInstance()->autoExecute(
		  _DB_PREFIX_.'pl_nivoslideshow',
		  array(
			'filename' => $filename,
			'link' => $link,
			'order' => (int)$order,
			'publish' => (int)$publish
		  ),
		  'INSERT'
		);
		
		// Insert ID
		$id_plnivo = Db::getInstance()->Insert_ID();

		// Add data on stmenu_lang table
		foreach($title as $id_lang=>$title)
		{
		  Db::getInstance()->autoExecute(
			_DB_PREFIX_.'pl_nivoslideshow_lang',
			array(
			  'id_plnivo'=>$id_plnivo,
			  'id_lang'=>$id_lang,
			  'title'=>$title,
			  'description' => $description[$id_lang]
			),
			'INSERT'
		  );
		}
	}
	
	private function edit($id_plnivo, $filename, $title, $link, $description, $publish)
	{
		global $cookie;
		$cs = $this->get($id_plnivo, $cookie->id_lang);
		
		if($filename) {
		  unlink(dirname(__FILE__).'/img/'.$cs[0]['filename']);
		}
		
		// Update data on pl_nivoslideshow table
		$queryUpdate = 'UPDATE `'._DB_PREFIX_.'pl_nivoslideshow`
				SET 
				`link` = "'. $link .'", ';		
		if ($filename) $queryUpdate .= ' `filename` = "'.$filename.'", ';
		$queryUpdate .=	'`publish` = "'. intval($publish) .'" WHERE `id_plnivo` = "'.intval($id_plnivo).'"';

		Db::getInstance()->Execute($queryUpdate);
		
		foreach($title as $id_lang=>$title)
		{
			$queryUpdateName = 'UPDATE `'._DB_PREFIX_.'pl_nivoslideshow_lang`
				SET `title` = "'. $title .'",
					`description` = "'. $description[$id_lang] .'"
				WHERE `id_lang` = '.intval($id_lang) .' AND `id_plnivo` = '.intval($id_plnivo);
			
			Db::getInstance()->Execute($queryUpdateName);
		}		
	}
	
	private function remove ($id_plnivo)
	{
		global $cookie;
		$cs = $this->get($id_plnivo, $cookie->id_lang);

		unlink(dirname(__FILE__).'/img/'.$cs[0]['filename']);
		Db::getInstance()->delete(_DB_PREFIX_.'pl_nivoslideshow', "id_plnivo = '{$id_plnivo}'");
		Db::getInstance()->delete(_DB_PREFIX_.'pl_nivoslideshow_lang', "id_plnivo = '{$id_plnivo}'");
	}
	
	public function gets($id_lang=NULL, $id_plnivo=NULL, $publish=NULL)
	{
		return Db::getInstance()->ExecuteS('
			SELECT i.id_plnivo, i.filename, i1.title, i.link, i1.description, i.order, i.publish
			FROM '._DB_PREFIX_.'pl_nivoslideshow i 
			LEFT JOIN '._DB_PREFIX_.'pl_nivoslideshow_lang i1 ON (i.id_plnivo = i1.id_plnivo AND i1.id_lang = "'.$id_lang.'") WHERE 1=1
			'.((!is_null($id_plnivo)) ? ' AND i.id_plnivo = "'.$id_plnivo.'"' : '').'
			'.((!is_null($publish)) ? ' AND i.publish = "'.$publish.'"' : '').'	
			Order by i.`order`, i.`id_plnivo`
		');
	}

	public function get($id_plnivo, $id_lang)
	{
		return $this->gets($id_lang, $id_plnivo);
	}
	
	private function displayTableNivoSlideshow()
	{
    	global $cookie, $currentIndex;		
		$tablelistNivo = '';
		$irow = 0;
		
		$listNivos = $this->gets($cookie->id_lang);

		$count = 0;
		if (count($listNivos)) {
			foreach($listNivos as $listNivo) {
				$tablelistNivo .= '<tr id="tr_0_'.$listNivo['id_plnivo'].'_'.$listNivo['order'].'" '.($irow++ % 2 ? 'class="alt_row"' : '').'>';
				$tablelistNivo .= '<td class="center pointer dragHandle">
								<a'.(($listNivo['order'] == (count($listNivos) - 1) OR count($listNivos) == 1) ? ' style="display: none;"' : '').' href="'.$currentIndex.'&configure=prestalovenivoslideshow&id_plnivo='.$listNivo['id_plnivo'].'&way=1&order='.(int)($listNivo['order'] + 1).'&token='.Tools::getAdminTokenLite('AdminModules').'">
								<img src="../img/admin/down.gif" alt="'.$this->l('Down').'" title="'.$this->l('Down').'" /></a>
								<a'.($listNivo['order'] == 0 ? ' style="display: none;"' : '').' href="'.$currentIndex.'&configure=prestalovenivoslideshow&id_plnivo='.$listNivo['id_plnivo'].'&way=0&order='.(int)($listNivo['order'] - 1).'&token='.Tools::getAdminTokenLite('AdminModules').'">
								<img src="../img/admin/up.gif" alt="'.$this->l('Up').'" title="'.$this->l('Up').'" /></a>
							</td>';
				$tablelistNivo .= '<td><img src="'. _MODULE_DIR_ . $this->name.'/img/'.$listNivo['filename'].'" title="'. $listNivo['filename'] .'" width="100"/></td>';
				$tablelistNivo .= '<td>'.$listNivo['title'].'</td>';
				$tablelistNivo .= '<td>'.$listNivo['link'].'</td>';
				$tablelistNivo .= '<td>'.html_entity_decode($listNivo['description']).'</td>';
				$tablelistNivo .= '<td>'.$listNivo['publish'].'</td>';
				$tablelistNivo .= '<td> <form action="'.$_SERVER['REQUEST_URI'].'" method="post">
					<input type="hidden" name="id_plnivo" value="'.$listNivo['id_plnivo'].'" />
					<button name="submitPrestaLoveNivoEdit" class="button"><img src="../img/admin/edit.gif" alt="Edit" title="Edit" /></button>
					<button name="submitPrestaLoveNivoRemove" class="button" onclick="javascript:return confirm(\''.$this->l('Are you sure you want to remove this item?').'\');" ><img src="../img/admin/delete.gif" alt="Delete" title="Delete" /></button>
					</form></td>';
				$tablelistNivo .= '</tr>';			
			}
		}

		return $tablelistNivo;
	}
		
	private function displayCS()
	{
    	global $cookie;
		$css = $this->gets($cookie->id_lang, NULL, 1);
		for($i=0; $i<count($css); $i++) {
			$css[$i]['description'] = html_entity_decode($css[$i]['description']);
		}

		return $css;
	}
	
	public function hookTop($param)
	{
		global $smarty;
		$this->_listNivo = $this->displayCS();
		
		$theme = Configuration::get('PRESTALOVE_NIVO_THEME');
		$width = intval(Configuration::get('PRESTALOVE_NIVO_IMAGE_WIDTH'));
		$height = intval(Configuration::get('PRESTALOVE_NIVO_IMAGE_HEIGHT'));
		$smarty->assign('LISTNIVO', $this->_listNivo);
		
		$smarty->assign('WIDTH', $width);
		$smarty->assign('HEIGHT', $height);
		$smarty->assign('THEME', $theme);
    	return $this->display(__FILE__, 'prestalovenivoslideshow.tpl');
	}
	
	public function hookHome($params)
	{
		return $this->hookTop($params);
	}
	public function hookHeader($params)
	{
		global $smarty;		
		
		$theme = Configuration::get('PRESTALOVE_NIVO_THEME');
		$effect = Configuration::get('PRESTALOVE_NIVO_EFFECT');
		$boxCols = Configuration::get('PRESTALOVE_NIVO_COLS');
		$boxRows = Configuration::get('PRESTALOVE_NIVO_ROWS');
		$time_delay = intval(Configuration::get('PRESTALOVE_NIVO_TIMER_DELAY'));
		$speed = intval(Configuration::get('PRESTALOVE_NIVO_SPEED'));
		$auto_start = intval(Configuration::get('PRESTALOVE_NIVO_AUTO_START'));
		$controlNav = intval(Configuration::get('PRESTALOVE_NIVO_NAV'));
		$navThumbs = intval(Configuration::get('PRESTALOVE_NIVO_NAVTHUMBS'));
		$pauseOnHover = Configuration::get('PL_NIVO_PAUSE_SLIDE_HOVER');
		$directionNav = intval(Configuration::get('PRESTALOVE_NIVO_CONTROLS'));
		$directionNavHide = Configuration::get('PL_NIVO_HIDE_CONTROLS_HOVER');
		
		if(!$auto_start) $time_delay = 10000000;
		// Add Javascript code
		$nivo_js = '
		<script type="text/javascript">
			$(document).ready(function () {
				$(".pl-nivoslideshow").nivoSlider({
				pauseTime: '.$time_delay.',
				effect: "'.$effect.'",
				boxCols: "'.$boxCols.'",
				boxRows: "'.$boxRows.'",';
		if(!$pauseOnHover)		$nivo_js .= 'pauseOnHover: false,';
		if(!$controlNav)		$nivo_js .= 'controlNav: false,';
		if(!$directionNav)		$nivo_js .= 'directionNav: false,';
		if(!$directionNavHide)	$nivo_js .= 'directionNavHide: false,';
		
		$nivo_js .= '
				animSpeed: '.$speed.'
				});
			});
		</script>
		';

		$smarty->assign('nivo_js', $nivo_js);
		$smarty->assign('THEME', $theme);
		
		return $this->display(__FILE__, 'prestalovenivoslideshow-header.tpl');
	}
}
?>